const App = {
  mixins: [Save],//配置文件，路径/utils/mixins.js
  data() {
    return {
      ID_Card: [],
      dataForm: {
        Party_Member_SerialNumber: '',
        Personal_Resource: '4',
        Political_Affiliation: '政府人员'
      },
      dataForm1: {
        Personal_Resource: '4',
        Political_Affiliation: '政府人员'
      },
      rules: {
        // 身份证编号验证（空值+格式）
        ID_Card_Number: [
          {
            required: true,
            message: "身份证编号不能为空",
            trigger: "blur",
          },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: "身份证格式不正确",
            trigger: "blur",
          },
        ],
        Position: [        // 党内职务（空值校验）
          {
            required: true,
            message: "请选择党内职务",
            trigger: "change",
          },
        ],
        // 入党日期（空值+日期格式）
        Joining_Date: [
          {
            required: true,
            message: "请选择加入日期",
            trigger: "change",
          },
          {
            type: "date",
            message: "日期格式不正确",
            trigger: "change",
          },
        ],
        // 转正日期（空值+日期格式）
        Conformation_Date: [
          {
            required: true,
            message: "请选择转正日期",
            trigger: "change",
          },
          {
            type: "date",
            message: "日期格式不正确",
            trigger: "change",
          },
        ],
        Party_Organization_SerialNumber: [
          {
            required: true,
            message: "党组织不能为空",
            trigger: "blur",
          },
        ],
      },
      Manager: [],
      Nation: [],
      Ducation: ducation(),
      village: [],
      cityValue: [],
      cityValue1: [],
      city: [],
      city1: [],
      Category: [],
      is: false,
    };
  },
  mounted() {
    this.getCategory();
  },
  watch: {
    'dataForm.ID_Card_Number'(val) {
      this.dataForm1.ID_Card_Number = val;
    },
    'dataForm.Party_Member_SerialNumber'() {
      if (this.action == 'Modify') {
        $.ajax({
          headers: requestHeaders(),
          url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
          method: "post",
          data: {
            Data: "personal_information", //表名
            Condition: "ID_Card_Number='" + this.dataForm.ID_Card_Number + "'",
          },
          success: (res) => {
            if (res.length == 1) {
              $.ajax({
                url: `${absolutepath()}api/Districtjl.json`,
                method: "get",
                success: (data) => {
                  data.forEach(item => {
                    item.children.forEach(ite => {
                      ite.children.forEach(it => {
                        it.children = undefined
                      })
                    })
                  })
                  this.city = data;
                  if (this.action == 'Modify') {
                    this.dataForm1 = res[0];
                    this.cityValue = [this.dataForm1.RR_Province_Number, this.dataForm1.RR_City_Number, this.dataForm1.RR_County_Nubmer];
                    this.changeCity(this.cityValue,false);
                    this.cityValue1 = [this.dataForm1.RR_Town_Number, this.dataForm1.RR_Village_Number];
                  }
                },
              });
              
              this.is = false;
            } else {
              this.is = true;
            }
          },
          complete: (XMLHttpRequest) => {
            requestPretreatment(XMLHttpRequest);
          },
        });
      }
    }
  },
  methods: {
    shibie(val) {
      if (this.action == 'Add') {
        $.ajax({
          headers: requestHeaders(),
          url: `${mh}/generalBusiness/generalQueryByTableName`,
          method: "post",
          data: {
            Data: "personal_information", //表名
            Condition: "ID_Card_Number='" + val + "'",
          },
          success: (res) => {
            if (res.length == 1) {
              this.dataForm1 = res[0];
              this.cityValue = [this.dataForm1.RR_Province_Number, this.dataForm1.RR_City_Number, this.dataForm1.RR_County_Nubmer];
              this.cityValue1 = [this.dataForm1.RR_Town_Number, this.dataForm1.RR_Village_Number];
              this.is = false;
            
            } else {
              // this.dataForm1 = {};
              
              this.is = true;
            }
          },
          complete: (XMLHttpRequest) => {
            requestPretreatment(XMLHttpRequest);
          },
        });
      }
    },
    changeCity1(val) {
      if (val.length > 0) {
        let Town = this.city1.filter(i => i.ProvinceNumber == val[0])[0];
        let Village = Town.children.filter(i => i.ProvinceNumber == val[1])[0];
        let arr = this.dataForm1.Registered_Residence.split('/');
        this.dataForm1.Registered_Residence = arr[0] + '/' + arr[1] + '/' + arr[2] + '/' + Town.Province + '/' + Village.Province;
        this.dataForm1.RR_Town_Number = val[0];
        this.dataForm1.RR_Village_Number = val[1];
      } else {
        this.dataForm1.RR_Town_Number = '';
        this.dataForm1.RR_Village_Number = '';
      }
    },
    changeCity(val,is=true) {
      console.log(val);
      if (val.length > 0) {
        let Province = this.city.filter(i => i.value == val[0])[0];
        let City = Province.children.filter(i => i.value == val[1])[0];
        let County = City.children.filter(i => i.value == val[2])[0];
        this.dataForm1.Registered_Residence = Province.label + '/' + City.label + '/' + County.label;
        this.dataForm1.RR_Province_Number = val[0];
        this.dataForm1.RR_City_Number = val[1];
        this.dataForm1.RR_County_Nubmer = val[2];
        if (is) {
          this.dataForm1.RR_Town_Number = '';
          this.dataForm1.RR_Village_Number = '';
          this.cityValue1 = [];
        }
        
        if (val.length > 0) {
          console.log(val[2]);
          $.ajax({
            headers: requestHeaders(),
            url: `${mh}/clientOperation/getDistrictTree`,
            type: "GET",
            data: {
              DistrictCode: val[2]
            },
            success: (data) => {
              this.city1 = data[0].children;
            },
            complete: (XMLHttpRequest) => {
              requestPretreatment(XMLHttpRequest);
            },
            dataType: "json",
          });
        }
      } else {
        this.dataForm1.Registered_Residence = '';
        this.dataForm1.RR_Province_Number = '';
        this.dataForm1.RR_City_Number = '';
        this.dataForm1.RR_County_Nubmer = '';
        this.dataForm1.RR_Town_Number = '';
        this.dataForm1.RR_Village_Number = '';
        this.cityValue1 = [];
      }
    },
    async handleSubmit() {
      const allValid = await this.validateAllForms();
      if (allValid) {
        this.loading = true;
        let ls_URL = window.location.href;
        const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
        let lJSONObject_Data_Options = new Object();
        lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

        let ls_MainTableName = lJSONObject_Data_Options.TableName;
        let ls_DataForm = lJSONObject_Data_Options.form;
        let ls_primary_key = lJSONObject_Data_Options.primary_key;
        //没有子表下面内容就会报错，try/catch抛出异常
        try {
          //可能涉及多个子表
          document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
            let lJSONObject_ChildData_Options = new Object();
            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
            if (this[ls_DataForm][ls_primary_key]) {
              this[ls_ChildDataForm].forEach(item => {
                item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
              })
            }
            //建立子表结构体
            let JSONArray_ChildRecord = new Array();
            JSONArray_ChildRecord = this[ls_ChildDataForm];
            if (!this[ls_DataForm].Children) {
              this[ls_DataForm].Children = new Object();
            }
            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
          })
        } catch (error) {

        }
        //建立新增提交结构
        let lJSONObject_DataSet = new Object();
        if (action == 'Add') {
          if (this.nodeKey) {
            this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
          }
          let lJSONObject_Table = new Object();
          if (this.is) {
            this['dataForm1'].Migrant_Personal = (this['dataForm1'].RR_County_Nubmer == '232723' ? '0' : '1')
            this['dataForm1']['Children'] = {
              government_member_information: [deepClone(this[ls_DataForm])]
            }
            let lJSONArray_Record = new Array();
            lJSONArray_Record.push(this['dataForm1']);
            lJSONObject_Table['personal_information'] = lJSONArray_Record;
            //手机号不能有重复
            lJSONObject_Table['personal_Contact_Phone'] = [{ Contact_Phone: this['dataForm1'].Contact_Phone }];
          } else {
            let lJSONArray_Record = new Array();
            lJSONArray_Record.push(this[ls_DataForm]);
            lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
          }
          lJSONObject_DataSet[action] = lJSONObject_Table;
        } else if (action == 'Modify') {
          const { add, modify } = this.deal(this[ls_DataForm]);
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(modify);

          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

          lJSONObject_Table['personal_information'] = [this.dataForm1];

          lJSONObject_DataSet[action] = lJSONObject_Table;
          if (add != null) {
            let lJSONArray_Record_Add = new Array();
            lJSONArray_Record_Add.push(add);

            let lJSONObject_Table_Add = new Object();
            lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

            lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
          }
          if (this[ls_DataForm].Party_Member_Category_SerialNumber != this[ls_DataForm].Party_Member_Category_SerialNumber_Original) {
            let party_member_category_log = [{
              Party_Member_Category_SerialNumber: this.dataForm.Party_Member_Category_SerialNumber,
              Party_Member_SerialNumber: this.dataForm.Party_Member_SerialNumber,
            }]
            lJSONObject_DataSet['Add'] = {
              party_member_category_log
            }
          }
        }
        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
        if (!lJSONObject_DataSet['Add']) {
          lJSONObject_DataSet['Add'] = new Object();
        }
        lJSONObject_DataSet['Add']['base_operation_log'] = [{
          Operation_Type: '0',
          Operation_Path: this.relativePath,
          Operation_Main,
          Operation_Interface: "generalSave",
          Operation_IP: getIpAddress()
        }]


        submitSave(lJSONObject_DataSet, (res) => {
          if (res.Status == 'success') {
            window.location.href = './index.html'
          }
          this.loading = false;
        })
        // $.ajax({
        //   headers: requestHeaders(),
        //   url: `${mh}/generalBusiness/generalSave`,
        //   method: "post",
        //   data: {
        //     Data: JSON.stringify(lJSONObject_DataSet),
        //   },
        //   success: (res) => {
        //     if (res.Status == 'success') {
        //       window.location.href = './index.html'
        //     }
        //   },
        //   complete: (XMLHttpRequest) => {
        //     this.loading = false;
        //     requestPretreatment(XMLHttpRequest);
        //   },
        // });
      }
    },
    getCategory() {
      $.ajax({
        url: absolutepath() + "api/Nation.json",
        type: "GET",
        success: (data) => {
          this.Nation = data;
        },

        dataType: "json",
      });
      $.ajax({
        url: `${absolutepath()}api/Districtjl.json`,
        method: "get",
        success: (data) => {
          data.forEach(item => {
            item.children.forEach(ite => {
              ite.children.forEach(it => {
                it.children = undefined
              })
            })
          })
          this.city = data;
          if (this.action == 'Add') {
            this.cityValue = ['230000', '232700', '232723']
            this.changeCity(this.cityValue)
          }
        },
      });
      $.ajax({
        headers: requestHeaders(),
        type: "POST",
        url: mh + "/generalBusiness/generalQueryByTableName",
        data: {
          Data: "party_member_category", //指定要查询的数据库表名
          Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
        },
        success: (Result) => {
          this.Category = Result;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        type: "POST",
        url: mh + "/generalBusiness/generalQueryByTableNameWithOriginal",
        data: {
          Data: "personal_information", //指定要查询的数据库表名
          Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
        },
        success: (Result) => {
          this.ID_Card = Result;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
        type: "GET",
        data: {
          TableName: 'government_agencies',
          NodeCode: '',
        },
        success: (data) => {
          this.Manager = data; // 直接使用 this
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
  },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-cascader', ylCascader);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
